//
//  AFYSecctionsView.m
//  AFYTestProduct
//
//  Created by yzrs on 16/12/8.
//  Copyright © 2016年 ArtemisFang. All rights reserved.
//

#import "AFYSecctionsView.h"

@interface AFYSecctionsView ()<AFYSecctionsButtonDelegate>
{
    NSInteger       _secctionFlag;
    UIView          *_backGroundView;
}
//半透明背景
@property(nonatomic,strong)UIVisualEffectView *blurEffectView;
//半透明背景高度
@property(nonatomic,assign)CGFloat blurHeight;

@property(nonatomic,strong)UIWindow *backWindow;

@end

@implementation AFYSecctionsView


//创建 选择项view 默认字体和高宽
-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message secctionTexts:(NSArray *)secctionTexts andDelegate:(id<AFYSecctionsViewDelegate>)delegate
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, TheAFYWidth, TheAFYHeight);
        _backGroundView = [UIView viewWithSuperView:self andFrameBlock:^(UIView *view) {
            view.backgroundColor = UIColorFromRGB(0x000000);
            view.alpha = 0.3;
            view.frame = self.bounds;
            view.tag   = 1010;
        }];
        self.secctionTexts  = [secctionTexts mutableCopy];
        self.message        = message;
        self.title          = title;
        self.delegate       = delegate;
    }
    
    return self;
}

//创建 选择项view 给出字体和高宽
-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message secctionTexts:(NSArray *)secctionTexts andTextFont:(CGFloat)textFont andTextColor:(UIColor *)textColor andDelegate:(id<AFYSecctionsViewDelegate>)delegate
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, TheAFYWidth, TheAFYHeight);
        _backGroundView = [UIView viewWithSuperView:self andFrameBlock:^(UIView *view) {
            view.backgroundColor = UIColorFromRGB(0x000000);
            view.alpha = 0.3;
            view.frame = self.bounds;
            view.tag   = 1010;
        }];
        self.secctionTexts  = [secctionTexts mutableCopy];
        self.message        = message;
        self.title          = title;
        self.secctionTextColor = textColor;
        self.secctionTextFont  = [UIFont systemFontOfSize:textFont];
        self.delegate       = delegate;
    }
    
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, TheAFYWidth, TheAFYHeight);
        _backGroundView = [UIView viewWithSuperView:self andFrameBlock:^(UIView *view) {
            view.backgroundColor = UIColorFromRGB(0x000000);
            view.alpha = 0.3;
            view.frame = self.bounds;
            view.tag   = 1010;
        }];
    }
    return self;
}

//半透明效果
-(UIVisualEffectView *)blurEffectView{
    if (!_blurEffectView) {
        UIVisualEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _blurEffectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        _blurEffectView.userInteractionEnabled = YES;
    }
    
    return _blurEffectView;
}

//半透明背景高度
-(CGFloat)blurHeight{
    
    return _blurHeight;
}

//secctionHeight
-(CGFloat)secctionHeight{
    if (_secctionHeight == 0) {
        _secctionHeight = AFYSecctionViewCellHeight;
    }
    return _secctionHeight;
}

//背景window
-(UIWindow *)backWindow{
    if (!_backWindow) {
        _backWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backWindow.windowLevel = UIWindowLevelStatusBar;
        _backWindow.hidden = YES;
    }
    return _backWindow;
}


/* 1.0 字体大小  设置了self.secctionTextFont  self.textFont值默认为 20.0*/
-(UIFont *)secctionTextFont{
    if (!_secctionTextFont) {
        _secctionTextFont = AFYSecctionTextFont;
    }
    return _secctionTextFont;
}

-(UIFont *)titleFont{
    if (!_titleFont) {
        _titleFont = AFYSecctionTitleFont;
    }
    return _titleFont;
}

-(UIFont *)messageFont{
    if (!_messageFont) {
        _messageFont = AFYSecctionMessageFont;
    }
    return _messageFont;
}

/* 2.0 字体颜色  设置了self.secctionTextColor  self.textColor值默认为 0x909090 */
-(UIColor *)secctionTextColor{
    if (!_secctionTextColor) {
        _secctionTextColor = AFYSecctionTextColor;//UIColorFromRGB(0x909090);
    }
    return _secctionTextColor;
}

-(UIColor *)titleColor{
    if (!_titleColor) {
        _titleColor = AFYSecctionTitleColor;
    }
    return _titleColor;
}

-(UIColor *)messageColor{
    if (!_messageColor) {
        _messageColor = AFYSecctionMessageColor;
    }
    return _messageColor;
}


/* 3.0 解析secctionTexts结构  flag = 1 一维数组  flag = 2 二维数组 */
-(void)setSecctionTexts:(NSArray *)secctionTexts{
    
    if (![secctionTexts isKindOfClass:[NSArray class]] || secctionTexts.count == 0) {
        return;
    }
    
    _secctionFlag = 0;
    for (id value in secctionTexts) {
        if ([value isKindOfClass:[NSArray class]]) {
            for (id object in value) {
                if (![object isKindOfClass:[NSString class]]) {
                    return;
                }
            }
            _secctionFlag = 2;//二维数组
        }else{
            if (![value isKindOfClass:[NSString class]]) {
                return;
            }
        }
    }
    
    if (_secctionFlag == 0) {
        _secctionFlag = 1;//一维数组
    }
    
    _secctionTexts = secctionTexts;
}

/* X.0 创建选项 按钮 */
-(void)createSecctionViews{
    
    if (!self.secctionTexts.count) {
        return;
    }
    
    NSMutableArray *titleArray = [NSMutableArray array];
    if (_secctionFlag == 1) {
        [titleArray addObjectsFromArray:self.secctionTexts];
        [titleArray addObject:@""];
        [titleArray addObject:@"取消"];
    }else if (_secctionFlag == 2){
        for (NSArray *arrayTemp in self.secctionTexts) {
            [titleArray addObjectsFromArray:arrayTemp];
            [titleArray addObject:@""];
        }
        [titleArray addObject:@"取消"];
    }
    
    CGFloat viewHeight = [self createTitleAndMessageView];
    [self createSecctionButtonsWithTitles:titleArray andViewHeight:viewHeight];
    
}

-(void)createSecctionButtonsWithTitles:(NSArray *)titleArray andViewHeight:(CGFloat)viewHeight{
    CGFloat heightY = 0;
    if (viewHeight) {
        heightY = viewHeight + 0.5;
    }
    
    NSInteger section = 0;
    NSInteger row = 0;
    
    UIScrollView *scrollView;
    CGFloat scrollHeight = 0;
    if (titleArray.count > 6) {
        scrollView = [[UIScrollView alloc] init];
    }
    
    for (int i=0; i<titleArray.count; i++) {
        NSString *title  = [titleArray objectAtIndex:i];
        if ([title isEqualToString:@""]) {
            heightY += AFYSecctionViewCellGap;
            
            section++;
            row     = 0;
        }else{
            AFYSecctionsButton *button = [[AFYSecctionsButton buttonWithTitle:title andTitleColor:self.secctionTextColor andTitleFont:self.secctionTextFont.pointSize] setFrameBlock:^(UIView *view) {
                view.afy_size   = CGSizeMake(TheAFYWidth, self.secctionHeight - 0.5);
                view.afy_origin = CGPointMake(0, heightY);
                if (scrollView) {
                    if (i == titleArray.count - 1) {
                        [self.blurEffectView addSubview:view];
                    }else{
                        view.afy_origin = CGPointMake(0, heightY - viewHeight);
                        [scrollView addSubview:view];
                    }
                }else{
                    [self.blurEffectView addSubview:view];
                }
            }];
            
            if (i == 5) {
                scrollHeight = CGRectGetMaxY(button.frame) - viewHeight - self.secctionHeight - AFYSecctionViewCellGap;
            }
            if (scrollView && i == titleArray.count - 1){
                button.cb_top = scrollHeight + viewHeight + self.secctionHeight + AFYSecctionViewCellGap - button.cb_height;
            }
            //特殊选项字体颜色
            [button setButtonTitleColor:[self.specitalCellTextColorInfo objectForKey:title]];
            
            button.backgroundView01.frame = button.bounds;
            button.backgroundView02.frame = button.bounds;
            button.indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            button.delegate  = self;
            
            heightY += self.secctionHeight;
            row++;
        }
    }
    
    if (scrollView) {
        scrollView.frame = CGRectMake(0, viewHeight, TheAFYWidth, scrollHeight);
        scrollView.contentSize = CGSizeMake(TheAFYWidth, heightY - viewHeight - self.secctionHeight - AFYSecctionViewCellGap);
        
        [self.blurEffectView addSubview:scrollView];
        self.blurEffectView.afy_origin = CGPointMake(0, TheAFYHeight - scrollHeight - viewHeight);
        self.blurEffectView.afy_size   = CGSizeMake(TheAFYWidth, scrollHeight + viewHeight + self.secctionHeight + AFYSecctionViewCellGap);
    }else{
        self.blurEffectView.afy_origin = CGPointMake(0, TheAFYHeight - heightY);
        self.blurEffectView.afy_size   = CGSizeMake(TheAFYWidth, heightY);
    }
    
}

-(CGFloat)createTitleAndMessageView{
    
    if (self.title.length == 0 && self.message.length == 0) {
        return 0;
    }
    
    NSRange titleRange;
    NSRange messageRange;
    
    NSMutableString *titleMessage = [NSMutableString string];
    
    if (self.title && self.title.length) {
        [titleMessage appendString:self.title];
        titleRange.location = 0;
        titleRange.length   = self.title.length;
    }
    
    if (self.message && self.message.length) {
        
        if (titleRange.location == 0 && titleRange.length > 0) {
            [titleMessage appendString:@"\n"];
            [titleMessage appendString:self.message];
            messageRange.location = titleRange.length + 1;
            messageRange.length   = self.message.length;
        }else{
            
            [titleMessage appendString:self.message];
            messageRange.location = 0;
            messageRange.length   = self.message.length;
        }
        
        
    }
    
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:titleMessage];
    if (titleRange.location == 0 && titleRange.length > 0) {
        [attributeString addAttribute:NSFontAttributeName value:self.titleFont range:titleRange];
        [attributeString addAttribute:NSForegroundColorAttributeName value:self.titleColor range:titleRange];
    }
    
    if (messageRange.length == self.message.length) {
        [attributeString addAttribute:NSFontAttributeName value:self.messageFont range:messageRange];
        [attributeString addAttribute:NSForegroundColorAttributeName value:self.messageColor range:messageRange];
    }
    
    UILabel *titleMessageLabel = [[UILabel alloc] init];
    titleMessageLabel.numberOfLines = 0;
    titleMessageLabel.textAlignment = NSTextAlignmentCenter;
    
    [titleMessageLabel setAttributedText:attributeString];
    CGSize size = [titleMessageLabel sizeThatFits:CGSizeMake(TheAFYWidth - 40, CGFLOAT_MAX)];
    
    CGFloat viewHeight = size.height + 20;
    if (viewHeight < AFYSecctionViewCellHeight) {
        viewHeight = AFYSecctionViewCellHeight;
    }
    titleMessageLabel.afy_leftX  = 20;
    titleMessageLabel.afy_size   = CGSizeMake(TheAFYWidth - 40, size.height);
    titleMessageLabel.afy_centerY= viewHeight*0.5;
    
    [UIView viewWithSuperView:self.blurEffectView andBgColor:UIColorFromRGB(0xffffff) andFrameBlock:^(UIView *view) {
        view.alpha = 0.75;
        view.afy_origin = CGPointMake(0, 0);
        view.afy_size   = CGSizeMake(TheAFYWidth, viewHeight);
    }];
    
    [[[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]] setFrameBlock:^(UIView *view) {
        view.afy_origin = CGPointMake(0, 0);
        view.afy_size   = CGSizeMake(TheAFYWidth, viewHeight);
        [self.blurEffectView addSubview:view];
    }];
    
    [self.blurEffectView addSubview:titleMessageLabel];
    
    return viewHeight;
}


-(void)secctionButton:(UIButton *)button withIndexPath:(NSIndexPath *)indexPath{
    
    [self remove];
    
    if ((_secctionFlag == 1 && indexPath.section == 1) || (_secctionFlag == 2 && indexPath.section == self.secctionTexts.count)) {
        return;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(secctionView:selectTitleWithIndexPath:)]) {
        [self.delegate secctionView:self selectTitleWithIndexPath:indexPath];
    }
}


-(void)show{
    
    if (!self.secctionTexts.count) {
        return;
    }
    
    [self createSecctionViews];
    CGFloat height = self.blurEffectView.afy_height;
    self.blurEffectView.afy_topY = TheAFYHeight;

    [self addSubview:self.blurEffectView];
    [self.backWindow addSubview:self];
    [self.backWindow setHidden:NO];
    
    _backGroundView.alpha = 0;
    
    [UIView animateWithDuration:AFYAnimationTime animations:^{
        self.blurEffectView.afy_topY = TheAFYHeight - height;
        _backGroundView.alpha = 0.3;
    } completion:^(BOOL finished) {
        NSLog(@"Finished");
    }];
}


-(void)remove{
    
    [UIView animateWithDuration:AFYAnimationTime animations:^{
        self.blurEffectView.afy_topY = TheAFYHeight;
        _backGroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self.backWindow setHidden:YES];
    }];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UIView *touchView = [[touches anyObject] view];
    if (touchView == [self viewWithTag:1010]) {
        [self remove];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end







@implementation AFYSecctionsButton

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addSubview:self.backgroundView01];
        [self addSubview:self.backgroundView02];
        
        [self addTarget:self action:@selector(highlightAction:) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(unhighlightAction:) forControlEvents:UIControlEventTouchDragExit];
        [self addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

-(UIView *)backgroundView01{
    if (!_backgroundView01) {
        _backgroundView01 = [[UIView alloc]init];
        _backgroundView01.backgroundColor = [UIColor whiteColor];
        _backgroundView01.alpha = 0.75;
        _backgroundView01.userInteractionEnabled = NO;
        _backgroundView01.hidden = NO;
    }
    
    return _backgroundView01;
}

-(UIView *)backgroundView02{
    if (!_backgroundView02) {
        UIVisualEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        _backgroundView02 = blurEffectView;
        _backgroundView02.userInteractionEnabled = NO;
        _backgroundView02.hidden = NO;
    }
    return _backgroundView02;
}

-(void)highlightAction:(id)sender{
    _backgroundView01.alpha = 0.5;
}

-(void)unhighlightAction:(id)sender{
    _backgroundView01.alpha = 0.75;
}

//点击代理 响应事件
-(void)clickAction:(id)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(secctionButton:withIndexPath:)]) {
        [self.delegate secctionButton:self withIndexPath:self.indexPath];
    }
}

@end





